//
//  MyRequest.m
//  baodongPro
//
//  Created by feng on 16/3/4.
//  Copyright © 2016年 proper. All rights reserved.
//

#import "MyRequest.h"
#import <AFNetworking.h>


static MyRequest *_singleStance;
@implementation MyRequest
{
    NSMutableDictionary* _headConfigeDic;

}


/**
 *      @author 冯宝东
 *
 *      单例的封装
 *
 *      @return 网络工具类的实例
 */
+(instancetype)defultTool
{
    static dispatch_once_t onece=0;
    dispatch_once(&onece, ^{
        if (!_singleStance)
        {
            _singleStance=[[self alloc] init];
        }
    });

    return _singleStance;
}
/**
 *      @author 冯宝东
 *
 *      配置请求头
 *
 *      @param dic 请求头的信息
 */
+(void)setRequestManagerHeade:(NSMutableDictionary*)dic
{
    [[self defultTool] setRequestManagerHeade:dic];
}

-(void)setRequestManagerHeade:(NSMutableDictionary*)dic
{
    _headConfigeDic=dic;
}
/**
 *      @author 冯宝东
 *
 *      清除请求Request头部信息Dic
 */
-(void)clearRequestManagerHeaderDic;
{
    _headConfigeDic=nil;

}

-(AFHTTPSessionManager *)baseHttpSessionManager{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if (_headConfigeDic)
    {
        NSArray*keyArray=  [_headConfigeDic allKeys];
        NSArray*valueArray=  [_headConfigeDic allValues];
        for (int i=0; i<keyArray.count; i++)
        {
            NSString* keyS=[keyArray objectAtIndex:i];
            NSString* valueS=[valueArray objectAtIndex:i];
            [manager.requestSerializer setValue:valueS forHTTPHeaderField:keyS];
            
        }
//        [_headConfigeDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
//            
//            [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
//            
//        }];
        
    }
 
    [manager.requestSerializer setTimeoutInterval:60];
    //header 设置
    //    [manager.requestSerializer setValue:K_PASS_IP forHTTPHeaderField:@"Host"];
    //    [manager.requestSerializer setValue:@"max-age=0" forHTTPHeaderField:@"Cache-Control"];
    //    [manager.requestSerializer setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
    //    [manager.requestSerializer setValue:@"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3" forHTTPHeaderField:@"Accept-Language"];
    //    [manager.requestSerializer setValue:@"gzip, deflate" forHTTPHeaderField:@"Accept-Encoding"];
    //        [manager.requestSerializer setValue:@"keep-alive" forHTTPHeaderField:@"Connection"];
    //    [manager.requestSerializer setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:35.0) Gecko/20100101 Firefox/35.0" forHTTPHeaderField:@"User-Agent"];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"application/json", nil];
    return manager;
}

-(AFURLSessionManager*)baseURLSessionManager
{
    AFURLSessionManager* manager=[[AFURLSessionManager alloc] initWithSessionConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration]];

    
    return manager;
}

/**
 *      @author 冯宝东
 *
 *      GET 请求方法
 *
 *      @param GetURL        url HostUrl
 *      @param paramDic      参数
 *      @param mySuccess     成功回调
 *      @param myFailedBlock 失败回调
 */

-(void)getRequestWithURL:(NSString*)GetURL withParameterDic:(NSMutableDictionary*)paramDic withSuccessed:(successedBlock)mySuccess withFailedBclock:(failedBlock)myFailedBlock withPerBlock:(percentageBlock)myPerBlock
{

    AFHTTPSessionManager* manager=[self baseHttpSessionManager];
    [manager GET:GetURL parameters:paramDic progress:^(NSProgress * _Nonnull downloadProgress) {
        
        int64_t  allData=downloadProgress.totalUnitCount;
        int64_t  downedData=downloadProgress.completedUnitCount;
        CGFloat per=(downedData*100.0)/(allData*100.0);
        myPerBlock(per);

        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode= response.statusCode;
        if (statusCode==200&&responseObject)
        {
            mySuccess(responseObject);
            
        }
        
    [self clearRequestManagerHeaderDic];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        myFailedBlock(error);
        NSLog(@"%@",error.domain);                            // 错误的网址
        NSLog(@"%@",error.localizedDescription);             //  错误描述
        NSLog(@"%@",error.localizedFailureReason);          //   错误的原因
        NSLog(@"%@",error.localizedRecoverySuggestion);    //    修正错误建议
    [self clearRequestManagerHeaderDic];
        
    }];
    



}

/**
 *      @author 冯宝东
 *
 *      POST  请求方法
 *
 *      @param PostURL       post  HostUrl
 *      @param paramDic      参数
 *      @param mySuccess     成功回调
 *      @param myFailedBlock 失败回调
 */
-(void)postRequestWithURL:(NSString*)PostURL withParameterDic:(NSMutableDictionary*)paramDic withSuccessed:(successedBlock)mySuccess withFailedBclock:(failedBlock)myFailedBlock withPerBlock:(percentageBlock)myPerBlock
{

    AFHTTPSessionManager*manager=[self  baseHttpSessionManager];
    [manager POST:PostURL parameters:paramDic progress:^(NSProgress * _Nonnull uploadProgress) {
        int64_t  allData=uploadProgress.totalUnitCount;
        int64_t  downedData=uploadProgress.completedUnitCount;
        CGFloat per=(downedData*100.0)/(allData*100.0);
        myPerBlock(per);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
        NSInteger statusCode= response.statusCode;
        if (statusCode==200&&responseObject)
        {
            mySuccess(responseObject);
            
        }
        [self clearRequestManagerHeaderDic];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        myFailedBlock(error);
        NSLog(@"%@",error.domain);                            // 错误的网址
        NSLog(@"%@",error.localizedDescription);             //  错误描述
        NSLog(@"%@",error.localizedFailureReason);          //   错误的原因
        NSLog(@"%@",error.localizedRecoverySuggestion);    //    修正错误建议
        
        [self clearRequestManagerHeaderDic];
        
    }];



}















@end
